const formatTime = (timestamp, type) => {
  var date = new Date(timestamp);
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
  month = month > 9 ? month : '0' + month;
  day = day > 9 ? day : '0' + day;
  hour = hour > 9 ? hour : '0' + hour;
  minute = minute > 9 ? minute : '0' + minute;
  second = second > 9 ? second : '0' + second;
  var dateString = year + '-' + month + '-' + day;
  var timeString = hour + ':' + minute + ':' + second;
  if (type === 'date') {
    return dateString
  } else if (type === 'time') {
    return dateString + ' ' + timeString;
  }
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

const Util = {
  jsonSort: (jsonObj) => {
    const arr = [];
    for (const key in jsonObj) {
      if (Object.prototype.hasOwnProperty.call(jsonObj, key)) {
        if (jsonObj[key]) {
          arr.push(key);
        }
      }
    }
    arr.sort();
    let str = '';
    for (const key in arr) {
      if (Object.prototype.hasOwnProperty.call(arr, key)) {
        const element = arr[key];
        str += element + '-' + jsonObj[element] + '|';
      }
    }
    return str.substring(0, str.length - 1);
  },
  trimNulls: (jsonObj) => {
    const newJsonObj = Object.assign({}, jsonObj);
    for (const key in newJsonObj) {
      if (Object.prototype.hasOwnProperty.call(newJsonObj, key)) {
        const element = newJsonObj[key];
        if (
          element === 'null' ||
          element === null ||
          element === '' ||
          typeof element === 'undefined' ||
          (element instanceof Object && Object.keys(element).length === 0)
        ) {
          delete newJsonObj[key];
        } else {
          newJsonObj[key] = element.toString().replace(/\s*/g, '');
        }
      }
    }
    return newJsonObj;
  },
  formatSearchParams: (jsonObj) => {
    const body = new URLSearchParams();
    for (const key in jsonObj) {
      if (Object.prototype.hasOwnProperty.call(jsonObj, key)) {
        const element = jsonObj[key];
        body.set(key, element);
      }
    }
    return body;
  },
  isMobile: () => {
    const flag = navigator.userAgent.match(
      /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|XiaoMi|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
    );
    return flag;
  },

  getBirth: (idCard) => {
    let birthday = '';
    if (idCard !== null && idCard !== '') {
      birthday = idCard.slice(6, 14);
    }
    birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
    return birthday;
  },
  getSex: (idCard) => {
    let sexIndex = 0;
    if (parseInt(idCard.slice(-2, -1)) % 2 == 1) {
      sexIndex = 0;
    }
    else {
      sexIndex = 1;
    }
    return sexIndex;
  },
  calculateAge: (idCard) => {
    const birthDate = idCard.substr(6, 8);
    const currentDate = new Date();
    const currentYear = currentDate.getFullYear();
    const currentMonth = currentDate.getMonth() + 1;
    const currentDay = currentDate.getDate();

    const yearDiff = currentYear - Number(birthDate.substr(0, 4));
    const monthDiff = currentMonth - Number(birthDate.substr(4, 2));
    const dayDiff = currentDay - Number(birthDate.substr(6, 2));

    let age = yearDiff;

    if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
      age--;
    }
    return age;
  },
  /**
   * 乘法
   * @param arg1
   * @param arg2
   * @returns
   */
  floatMul: (arg1, arg2) => {
    let m = 0,
      s1 = arg1.toString(),
      s2 = arg2.toString();
    try {
      m += s1.split('.')[1].length;
    } catch (e) { }
    try {
      m += s2.split('.')[1].length;
    } catch (e) { }
    return (
      (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) /
      Math.pow(10, m)
    );
  },

  /**
   * 除法
   * @param arg1
   * @param arg2
   * @returns
   */
  floatp: (arg1, arg2) => {
    let t1 = 0;
    let t2 = 0;
    let r1, r2, n;
    try {
      t1 = arg1.toString().split('.')[1].length;
    } catch (e) { }
    try {
      t2 = arg2.toString().split('.')[1].length;
    } catch (e) { }
    r1 = Number(arg1.toString().replace('.', ''));
    r2 = Number(arg2.toString().replace('.', ''));
    // n = (t1 >= t2) ? t1 : t2
    return Number(Number((r1 / r2) * Math.pow(10, t2 - t1)).toFixed(3));
  },

  /**
   * 加法
   * @param arg1
   * @param arg2
   * @returns
   */
  autoAdd: (arg1, arg2) => {
    let r1, r2, m;
    try {
      r1 = arg1.toString().split('.')[1].length;
    } catch (e) {
      r1 = 0;
    }
    try {
      r2 = arg2.toString().split('.')[1].length;
    } catch (e) {
      r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    return Number(
      (Util.floatMul(Number(arg1), m) + Util.floatMul(Number(arg2), m)) / m
    );
  },

  /**
   * 减法
   * @param arg1
   * @param arg2
   * @returns
   */
  autoReduce: (arg1, arg2) => {
    let r1, r2, m, n;
    try {
      r1 = arg1.toString().split('.')[1].length;
    } catch (e) {
      r1 = 0;
    }
    try {
      r2 = arg2.toString().split('.')[1].length;
    } catch (e) {
      r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    // 动态控制精度长度
    n = r1 >= r2 ? r1 : r2;
    return Number(
      (
        (Util.floatMul(Number(arg1), m) - Util.floatMul(Number(arg2), m)) /
        m
      ).toFixed(n)
    );
  },
};

module.exports = {
  formatTime,
  Util
}
